package com.car.customer.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class CustomCaptchaGenerator {

    private static final int WIDTH = 150;
    private static final int HEIGHT = 50;
    private static final int CHAR_COUNT = 4;
    private static String generatedCaptchaText;

    public static String generateCaptcha() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);

        g2d.setFont(new Font("Arial", Font.BOLD, 30));
        g2d.setColor(Color.BLACK);

        Random random = new Random();
        StringBuilder captchaText = new StringBuilder();
        for (int i = 0; i < CHAR_COUNT; i++) {
            int charValue = random.nextInt(26) + 65; // 生成大写字母 A-Z
            char captchaChar = (char) charValue;
            captchaText.append(captchaChar);
            int x = i * WIDTH / CHAR_COUNT + random.nextInt(20);
            int y = HEIGHT / 2 + random.nextInt(20);
            g2d.drawString(String.valueOf(captchaChar), x, y);
        }

        g2d.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", baos);
        } catch (IOException e) {
            e.printStackTrace();
        }

        generatedCaptchaText = captchaText.toString();
        return "data:image/png;base64," + java.util.Base64.getEncoder().encodeToString(baos.toByteArray());
    }

    public static String getGeneratedCaptchaText() {
        return generatedCaptchaText;
    }
}